#include "lib/web.cpp"
#include "lib/svg.cpp"
#include <dirent.h>

vector<string> find_apps(string ext=".cpp") {
	vector<string> apps;
	DIR* d = opendir("../../cpp");
	struct dirent* dir;
	while ((dir = readdir(d))) {
		string name = dir->d_name;
		int size = name.size();
		if (size>=1 and name.substr(0,1)==".") continue;
		if (size>=1 and name.substr(0,1)=="_") continue;
		if (name=="main"+ext) continue;
		if (size<4 or name.substr(size-4, size)!=ext) continue;
		name = name.substr(0, size-4);
		apps.push_back(name);
	}
	closedir(d);
	return apps;
}

void sort(vector<string> & v) {
	int n = v.size();
	I(i, n-1)
		I(j, n-1-i)
			if (v[j]>v[j+1])
				swap(v[j],v[j+1]);
}

string _2str(int d) {
	stringstream ss;
	ss << d;
	return ss.str();
}

int _2int(const string & s) {
	stringstream ss(s);
	int d;
	ss >> d;
	return d;
}

class Button : public SVG_Object {
	int x;
	int y;
	int width;
	int height;
	rect box;
	text name;
public:
	Button(string text, int x, int y, int width, int height) {
		this->x = x;
		this->y = y;
		this->width = width;
		this->height = height;
		box.x = _2str(x);
		box.y = _2str(y);
		box.rx = _2str(height/5);
		box.ry = _2str(height/5);
		box.width = _2str(width);
		box.height = _2str(height);
		box.fill = "#333366";
		box.stroke_width = _2str(0);
		name.x = _2str(x+height/2);
		name.y = _2str(y+height*2/3);
		name.stroke_width = _2str(0);
		name.fill = "white";
		name.content = text;
	}
	string html() const {
		return box.html()+name.html();
	}
	bool contains(int x, int y) {
		int offset_x = 10;
		int offset_y = 10;
		x -= offset_x;
		y -= offset_y;
		return x>=this->x and y>=this->y and
			x<=this->x+this->width and y<=this->y+this->height;
	}
};

int main()
{
	vector<string> apps = find_apps();
	sort(apps);
	vector<Button> buttons;
	SVG svg;
	I(i, apps.size()) {
		Button b(apps[i], 10, 10+i*40, 170, 30);
		buttons.push_back(b);
		svg += b;
	}
	cout << svg;

	data["mouse_request"] = "true";
	if (data.has("mouse_x")) {
		int x = _2int(data["mouse_x"]);
		int y = _2int(data["mouse_y"]);
		I(i, buttons.size()) {
			if (buttons[i].contains(x, y)) {
				data["app_request"] = "0 "+apps[i];
				break;
			}
		}

	}
}